package PipeStream;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @Author: ylc
 * @Description:管道流：用于线程之间传送数据
 * 一个线程发送数据到输出管道，另一个线程从输入管道中读取数据。
 *  PipeInputStream , PipeOutStream, PipeReader , PipedWriter。
 * @Date Created in 2022-05-14 21:05
 */
public class Test {
    public static void main(String[] args) throws IOException {
        /*定义管道字节流*/
        PipedInputStream  inputStream = new PipedInputStream();
        PipedOutputStream outputStream = new PipedOutputStream();

        inputStream.connect(outputStream);

        /*创建两个线程向管道流中读写数据*/
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    writeData(outputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    readData(inputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    /**
     * 定义方法向管道流中写入数据
     */
    public static void writeData(PipedOutputStream out) throws IOException {
        /*把0-100 之间的数写入管道中*/
        for (int i = 0; i < 100; i++) {
            String data = "" + i;
            out.write(data.getBytes()); //把字节数组写入到输出管道流中
        }
        out.close();
    }

    /**
     * 定义方法从管道中读取数据
     */
    public static void readData(PipedInputStream input) throws IOException {
        /*从管道中读取0-100*/
        byte[] bytes = new byte[1024];
        int len = input.read(bytes); //返回读到的字节数，如果没有读到任何数据返回-1
        while(len != -1){
            //把bytes数组中从0开始到len个字节转换为字符串打印出来
            System.out.println(new String(bytes,0,len));
            len = input.read(bytes); //继续从管道中读取数据
        }
        input.close();
    }

}
